package com.dengqi.mymodule.activity.fragment;

import android.os.Bundle;
import android.util.Log;
import android.widget.RadioButton;
import android.widget.RadioGroup;

import com.dengqi.mymodule.BaseActivity;
import com.dengqi.mymodule.R;
import com.dengqi.mymodule.fragment.TypeFragment;

import java.util.ArrayList;
import java.util.List;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;


public class ViewPagerActivity extends BaseActivity {


    private RadioGroup mRadioGroup;
    private List<Fragment> mFragments;
    private ViewPager viewPager;
    private ViewPagerAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_viewpager);

        mRadioGroup = findViewById(R.id.radioGroup);
        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                Log.e("---", "onCheckedChanged");
                RadioButton radio = group.findViewById(checkedId);
                viewPager.setCurrentItem(Integer.parseInt(radio.getTag().toString()));
            }
        });

        int count = mRadioGroup.getChildCount();

        mFragments = new ArrayList<>();
        for(int i=0;i<count;i++){
            Bundle bundle = new Bundle();
            bundle.putString("title", "type:"+i);
            mFragments.add(Fragment.instantiate(this, TypeFragment.class.getName(), bundle));
        }

        adapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPager = findViewById(R.id.viewPager);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                Log.e("---", "onPageSelected");
                ((RadioButton)mRadioGroup.getChildAt(position)).setChecked(true);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
        viewPager.setAdapter(adapter);

        adapter.setData(mFragments);
        adapter.notifyDataSetChanged();


        ((RadioButton)mRadioGroup.getChildAt(0)).setChecked(true);

    }

}
